package org.budo.dubbo.rpc.util;

import java.util.Arrays;

import org.budo.support.lang.util.StringUtil;

import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;

/**
 * @author lmw
 */
public class InvocationUtil {
    /**
     * TODO 每次都执行？
     */
    public static String invocationToRequestUri(Invocation invocation) {
        Invoker<?> invoker = invocation.getInvoker();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(invoker.getInterface().getName()); // TODO GenericService 处理
        stringBuilder.append(".");
        stringBuilder.append(invocation.getMethodName());
        stringBuilder.append("(");
        Class<?>[] parameterTypes = invocation.getParameterTypes();
        for (int i = 0; i < parameterTypes.length; i++) {
            if (i > 0) {
                stringBuilder.append(",");
            }

            Class<?> parameterType = parameterTypes[i];
            if (parameterType.isArray()) {
                Class<?> componentType = parameterType.getComponentType();
                String canonicalName = componentType.getCanonicalName();
                stringBuilder.append(canonicalName).append("...");
            } else {
                String parameterTypeName = parameterType.getName();
                stringBuilder.append(parameterTypeName);
            }
        }

        stringBuilder.append(")");
        return stringBuilder.toString();
    }

    public static String toString(Invocation invocation) {
        if (null == invocation) {
            return null;
        }

        String str = invocation.toString();
        if (str.length() < 1024) { // 长度较短，全部展示
            return str;
        }

        // 长度较长，简略展示
        String[] arguments = argumentsToString(invocation.getArguments());

        String str1 = "#65 [methodName=" + invocation.getMethodName() //
                + ", parameterTypes=" + Arrays.toString(invocation.getParameterTypes()) //
                + ", arguments=" + Arrays.toString(arguments) //
                + ", attachments=" + invocation.getAttachments() + "]";
        return str1;
    }

    private static String[] argumentsToString(Object[] arguments) {
        String[] args = new String[arguments.length];

        for (int i = 0; i < arguments.length; i++) {
            Object each = arguments[i];
            args[i] = null == each ? null : StringUtil.cutLeft(each.toString(), 1024);
        }

        return args;
    }
}